// weapp-adapter.js
// 微信小游戏适配器，提供浏览器环境的模拟

// 获取系统信息
const systemInfo = wx.getSystemInfoSync()

// 创建全局 canvas
const canvas = wx.createCanvas()
canvas.width = systemInfo.windowWidth
canvas.height = systemInfo.windowHeight

// 创建模拟的 document 对象
const documentObj = {
  createElement: function(tagName) {
    if (tagName === 'canvas') {
      return canvas
    }
    return null
  },
  body: {
    appendChild: function(element) {
      // 微信小游戏中不需要实际添加到 body
    }
  }
}

// 创建全局 window 对象
const windowObj = {
  innerWidth: canvas.width,
  innerHeight: canvas.height,
  devicePixelRatio: systemInfo.pixelRatio || 1,
  navigator: {
    userAgent: `Mozilla/5.0 (${systemInfo.platform}) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E8301 MicroMessenger/7.0.0 Language/zh_CN`
  }
}

// 添加 window 方法
const methods = {
  requestAnimationFrame: callback => setTimeout(callback, 1000 / 60),
  cancelAnimationFrame: id => clearTimeout(id)
}

// 添加构造函数
const constructors = {
  Image: () => wx.createImage(),
  Audio: () => wx.createInnerAudioContext(),
  XMLHttpRequest: () => wx.request,
  WebSocket: () => wx.connectSocket
}

// 添加定时器函数
const timers = {
  setTimeout: setTimeout.bind(null),
  setInterval: setInterval.bind(null),
  clearTimeout: clearTimeout.bind(null),
  clearInterval: clearInterval.bind(null)
}

// 使用 Object.defineProperty 设置全局属性
const defineGlobalProperty = (key, value, configurable = true) => {
  try {
    Object.defineProperty(GameGlobal, key, {
      value,
      writable: false,
      configurable
    })
  } catch (e) {
    console.warn(`Failed to define property ${key}:`, e)
  }
}

// 设置基础全局对象
defineGlobalProperty('canvas', canvas)

// 设置 window 对象
Object.keys(windowObj).forEach(key => {
  try {
    Object.defineProperty(windowObj, key, {
      value: windowObj[key],
      writable: false,
      configurable: true
    })
  } catch (e) {
    console.warn(`Failed to define window property ${key}:`, e)
  }
})

// 设置 document 对象
Object.defineProperty(windowObj, 'document', {
  value: documentObj,
  writable: false,
  configurable: true
})

// 添加方法到 window 对象
Object.assign(windowObj, methods, constructors, timers)

// 设置全局 window
defineGlobalProperty('window', windowObj)

// 设置其他全局属性
defineGlobalProperty('document', documentObj)

// 导出常用的全局变量
const exportGlobals = [
  'navigator',
  'XMLHttpRequest',
  'WebSocket',
  'Image',
  'Audio',
  'requestAnimationFrame',
  'cancelAnimationFrame',
  'setTimeout',
  'setInterval',
  'clearTimeout',
  'clearInterval'
]

exportGlobals.forEach(key => {
  defineGlobalProperty(key, windowObj[key])
})

// 导出全局对象供其他模块使用
export {
  canvas,
  windowObj as window,
  documentObj as document
} 